package com.lagou.hwhbase.client;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.*;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Init {
    Configuration conf = null;
    Connection conn = null;

    @Before
    public void init() throws IOException {
        //获取一个配置文件对象
        conf = HBaseConfiguration.create();

        conf.set("hbase.zookeeper.quorum", "linux121,linux122");
        conf.set("hbase.zookeeper.property.clientPort", "2181");
        //通过conf获取到hbase集群的连接
        conn = ConnectionFactory.createConnection(conf);
    }

    //创建hw表
    @Test
    public void dropAndCreateHomeworkTable() throws IOException {
        //获取HbaseAdmin对象用来创建表
        HBaseAdmin admin = (HBaseAdmin) conn.getAdmin();
        //创建Htabledesc描述器，表描述器
        final HTableDescriptor hwTable = new HTableDescriptor(TableName.valueOf("hw"));
        //指定列族
        hwTable.addFamily(new HColumnDescriptor("friends"));
        admin.createTable(hwTable);
        System.out.println("hw表创建成功！！");
    }

    //插入作业数据
    @Test
    public void putHomeworkData() throws IOException {
        //需要获取一个table对象
        final Table hwTable = conn.getTable(TableName.valueOf("hw"));
        List<Put> puts = new ArrayList<Put>();
        for (int i = 1; i <=10 ; i++) {
            for (int j = 1; j <=10 ; j++) {
                if(i==j)continue;
                String rowKey="uid"+i;
                String value="uid"+j;
                System.out.println("uid"+i+"  "+"uid"+j);
                //准备put对象
                final Put put = new Put(Bytes.toBytes(rowKey));//指定rowkey

                put.addColumn(Bytes.toBytes("friends"), Bytes.toBytes(value), Bytes.toBytes(value));
                puts.add(put);
            }
            System.out.println("-----------------------------------------------");
        }

        //插入数据，参数类型是put
        hwTable.put(puts);
        //准备list<puts>,可以执行批量插入
        //关闭table对象
        hwTable.close();
        System.out.println("插入数据到hw表成功！！");
    }

    //释放连接
    @After
    public void release() {
        if (conn != null) {
            try {
                conn.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
